<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<h1>
	<s:text name="welcome" />
</h1>

<p>
	<s:url id="localeEN" namespace="/" action="">
		<s:param name="request_locale">en</s:param>
	</s:url>
	<s:url id="localeDE" namespace="/" action="">
		<s:param name="request_locale">de</s:param>
	</s:url>
	<s:a href="%{localeEN}">English</s:a>
	<s:a href="%{localeDE}">German</s:a>
</p>

<s:if test="hasActionErrors()">
	<div id="fieldErrors">
		<s:actionerror />
	</div>
</s:if>

<s:form action="addMessage" namespace="/" method="post" name="myForm" theme="xhtml">
	<s:textfield name="message" size="40" maxlength="40" required="true" key="your.message-label" />
	<s:submit key="submit" />
</s:form>

<h2>Messages already saved to DB:</h2>
<ul id="messegaList"></ul>

<script type="text/javascript">
    $(function(){
        "use strict";
            
        var destinationUrl = "/service/message";
        
        $.ajax({
            url: destinationUrl,
            type: "GET",
            cache: false,
            dataType: "json",
                     
            success: function (data, textStatus, jqXHR){
                var docfrag, ul, li, i;
                console.log("message list retrieved from backend: OK");
                
                ul = document.getElementById("messegaList");
                
                docfrag = document.createDocumentFragment();
                if ($.isArray(data) && data.length){
                    for (i=0; i < data.length; i++){
                        li = document.createElement("li");
                        li.textContent = data[i].message;
                        docfrag.appendChild(li);
                    }
                    ul.appendChild(docfrag);
                }else{
                    li = document.createElement("li");
                    li.textContent = "No messages available";
                    ul.appendChild(li);
                }
                
            },
                     
            error: function (jqXHR, textStatus, errorThrown){
                console.error("message list retrieved from backend: ERROR (url = "+destinationUrl+")");
                console.error("HTTP STATUS: "+jqXHR.status +" for url = "+destinationUrl);
            },
                     
            complete: function(jqXHR, textStatus){
                //alert("complete");
                //i.e. hide loading spinner
            },
                     
            statusCode: {
                404: function() {
                    console.error("404 ERROR: REST service not found: "+destinationUrl);
                }
            }
        });
                 
        //event.preventDefault();
        return false;
    });
</script>
